package com.fyt.ZhongYaoApp.interceptors;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fyt.ZhongYaoApp.pojo.Result;
import com.fyt.ZhongYaoApp.utils.JwtUtil;
import com.fyt.ZhongYaoApp.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 令牌验证
        String token = request.getHeader("Authorization");
        try {

            // 从redis中获取相同的token
//            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//            String redisToken = ops.get(token);
//            if (redisToken == null) {
//                throw new RuntimeException();
//            }

            Map<String,Object> claims = JwtUtil.parseToken(token);
            // 将业务数据存储刀ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        }catch (SignatureVerificationException e){
            returnJson(response,"无效签名");
            e.printStackTrace();
        }catch (TokenExpiredException e){
            returnJson(response,"token已经过期");
            e.printStackTrace();
        }catch (AlgorithmMismatchException e){
            returnJson(response,"算法不一致");
            e.printStackTrace();
        }catch (Exception e){
            returnJson(response,"token无效");
            e.printStackTrace();
        }
        return false;
//        catch (Exception e) {
//            // 没有令牌,http响应状态码为401
//            response.setStatus(401);
//            //不放行
//            return false;
//        }

    }

    private void returnJson(HttpServletResponse response, String message) throws Exception{
        PrintWriter writer = null;
        // 注意点1：这边返回配置为josn格式
        response.setContentType("application/json;charset=UTF-8");
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("code",500005);
            result.put("state", "false");
            result.put("msg", message);
            writer = response.getWriter();
            // 注意点2，这样要用fastjson转换一下后，返回的前端才是格式化后的json格式
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }


}


